package com.ckf.login_wx.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Bill;
import com.ckf.login_wx.entity.Odd;
import com.ckf.login_wx.entity.Xinsell;
import com.ckf.login_wx.servic.BillService;
import com.ckf.login_wx.servic.OddService;
import com.ckf.login_wx.servic.SellService;
import com.ckf.login_wx.util.Idname;
import com.github.pagehelper.PageHelper;

@RestController
public class Billcontroller {
	@Autowired
    private BillService billService;
	@Autowired
    private SellService sellService;
	@Autowired
    private OddService OddService;
    @PostMapping("/addordincome")
    public Map<String, Object> addordincome(String source,String time,String remark,String money) throws ParseException{
        Map<String, Object> map = new HashMap<>();
        Bill bill=new Bill();
        bill.setOdd("TZ");
        bill.setMoney(Double.parseDouble(money));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(remark);
        bill.setStatus(1);
		if (billService.save(bill)){
            map.put("code",200);
            map.put("result","添加成功");
            System.out.println("添加成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
    @GetMapping("/incomelist")
    public Object incomelist(){
        Map<String, Object> map = new HashMap<>();
        List<Bill> list=billService.list();
        map.put("list", list);
        double sum=0.00;
        for (int i = 0; i < list.size(); i++) {
        	sum+=list.get(i).getTotal();
		}
        map.put("sum", sum);
        return map;
    }
    @GetMapping("/incomelistall")
    public Object incomelistall(){
        Map<String, Object> map = new HashMap<>();
        List<Bill> list =billService.list(new QueryWrapper<Bill>().eq("status", "1"));double sum=0.00;
        map.put("data", list);
        for (int i = 0; i < list.size(); i++) {
        	sum+=list.get(i).getMoney();
		}
        map.put("sum", sum);
        return map;
    }
    @GetMapping("/delebillbyid")
    public Object delebillbyid(Integer id,String pagenew){
    	billService.removeById(id);
        Integer i = Integer.parseInt(pagenew);
    	System.out.println(billService.list().size()+"***");
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.list();
    }
    @GetMapping("/ordbillbysearch")
    public Object ordbillbysearch(String search,String talk,String pagenew){//
        Integer i = Integer.parseInt(pagenew);
    	if(search.equals("时间")){
       	 	PageHelper.offsetPage((i-1)*5, 5);
    		return billService.seletime(talk);
    	}
//        QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
//        Map<String, Object> mapuser = new HashMap<>();
//        mapuser.put(Idname.getname(search),talk);
//        mapuser.put("source","货款");
//        queryWrapper.allEq(mapuser);
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.selectlike(Idname.getname(search), talk);
    }
    @GetMapping("/bill/search")
    public Object billsearch(String talk){
        Map<String, Object> map = new HashMap<>();
        List<Bill> list=billService.list(new QueryWrapper<Bill>().like("remark", talk).eq("status", "1"));
        map.put("list", list);
        double sum=0.00;
        for (int i = 0; i < list.size(); i++) {
        	sum+=list.get(i).getTotal();
		}
        map.put("sum", sum);
        return map;
    }
    @GetMapping("/ordbillbysearchall")
    public Object ordbillbysearchall(String search,String talk){//
    	if(search.equals("时间")){
    		return billService.seletime(talk);
    	}
//        QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
//        Map<String, Object> mapuser = new HashMap<>();
//        mapuser.put(Idname.getname(search),talk);
//        queryWrapper.allEq(mapuser);
        return billService.selectlike(Idname.getname(search), talk);
    }
    @GetMapping("/selebillbyid")
    public Object selebillbyid(String id){
    	Integer idint = Integer.parseInt(id);
        return billService.getById(idint);
    }
    @PostMapping("/upbillbyid")
    public Object upbillbyid(String id,String source,String time,String remark,String money) throws ParseException{
    	Map<String, Object> map = new HashMap<>();
        Integer i = Integer.parseInt(id);
        Bill bill=new Bill();
        bill.setOdd("TZ");
        bill.setId(i);
        bill.setMoney(Double.parseDouble(money));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(remark);
        bill.setStatus(1);
		if (billService.updateById(bill)){
            map.put("code",200);
            map.put("result","修改成功");
            System.out.println("修改成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
    @GetMapping("/selebillid")
    public Object selebillid(){
    	List<String> odd=new ArrayList<String>();
    	
    	for(int n=0;n<OddService.list().size();n++){
    		if(OddService.list().get(n).getOdd()!=0){
        		odd.add(OddService.list().get(n).getOdd()+"");
    		}
    	}
    	HashSet<String> set=new LinkedHashSet<>(odd);
    	for(String word:odd){
    	    set.add(word);
    	}
        return set;
    }
//    @GetMapping("/selebillid")
//    public Object selebillid(){
//    	List<String> odd=new ArrayList<String>();
//    	for(int n=0;n<billService.list().size();n++){
//    		if(billService.list().get(n).getOdd()!=null&&!billService.list().get(n).getOdd().equals("")){
//        		odd.add(billService.list().get(n).getOdd());
//    		}
//    	}
//    	HashSet<String> set=new LinkedHashSet<>(odd);
//    	for(String word:odd){
//    	    set.add(word);
//    	}
//        return set;
//    }
    @GetMapping("/selebillbyoddall")
    public Object selebillbyoddall(String talk){
    	QueryWrapper<Bill> queryWrapper0 = new QueryWrapper<>();
        Map<String, Object> mapuser0 = new HashMap<>();
    	if(talk.equals("")||talk==null){
            mapuser0.put("source","货款");
            queryWrapper0.allEq(mapuser0);
            return billService.list(queryWrapper0);
        }
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        	mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
        return billService.list(queryWrapper);
    }
    @GetMapping("/selebillbyodd")
    public Object selebillbyodd(String pagenew,String talk){
        Map<String, Object> map = new HashMap<>();double sum=0.00;
        List<Bill> list=billService.list(new QueryWrapper<Bill>().like("odd", talk).eq("status", "1").eq("source","货款"));
        map.put("data", list);
        for (int i = 0; i < list.size(); i++) {
        	sum+=list.get(i).getMoney();
		}
        map.put("sum", sum);
        return map;
    }
    @PostMapping("/addbill")
    public Map<String, Object> addbill(String total,String debt,String time,String odd,String money,String saisie,String status) throws ParseException{
        Map<String, Object> map = new HashMap<>();
    	Odd oddentity=OddService.list(new QueryWrapper<Odd>().eq("odd", odd)).get(0);
        Bill bill=new Bill();
        bill.setOdd(odd);
        bill.setMoney(Double.parseDouble(money));
        bill.setTotal(Double.parseDouble(total));
        bill.setDebt(Double.parseDouble(debt));
        bill.setSource("货款");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(odd);
        bill.setAnq(oddentity.getAnq());
        bill.setPhone(oddentity.getPhone());
        bill.setName(oddentity.getName2());
        bill.setSaisie(saisie);
        bill.setStatus(Integer.parseInt(status));
		if (billService.save(bill)){
            map.put("code",200);
            map.put("result","添加成功");
            System.out.println("添加成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
    @GetMapping("/selebilltotal")
    public Object selebilltotal(String talk){
    	double total=0,debt=0;
    	Map<String, Object> map = new HashMap<>();
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
    	System.out.println(billService.list(queryWrapper).size()+"***");
    	for(int n=0;n<billService.list(queryWrapper).size();n++){
    		total=billService.list(queryWrapper).get(n).getTotal();
    		debt=billService.list(queryWrapper).get(n).getDebt();
    	}
        map.put("total",total);
        map.put("debt",debt);
    	
        return map;
    }
    @GetMapping("/delebillbyodd")
    public Object delebillbyodd(Integer id,String pagenew,String talk){
    	billService.removeById(id);
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
    	Integer i = Integer.parseInt(pagenew);
    	System.out.println(billService.list(queryWrapper).size()+"***");
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.list(queryWrapper);
    }
    @GetMapping("/ordbillbyoddsearch")
    public Object ordbillbyoddsearch(String talk,String pagenew){//
        Integer i = Integer.parseInt(pagenew);
        QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        if(!talk.equals("")&&talk!=null){
        	mapuser.put("odd",talk);
        }
        mapuser.put("source","货款");
        queryWrapper.allEq(mapuser);
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.list(queryWrapper);
    }
    @GetMapping("/seleoddbymoney")
    public Object seleoddbymoney(String talk){
    	double money=0;
    	Map<String, Object> map = new HashMap<>();
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
    	for(int n=0;n<billService.list(queryWrapper).size();n++){
    		money=money+billService.list(queryWrapper).get(n).getMoney();
    	}
        map.put("money",money);
    	
        return map;
    }
    @GetMapping("/seleoddbymoneyall")
    public Object seleoddbymoneyall(){
    	double money=0;
    	Map<String, Object> map = new HashMap<>();
    	for(int n=0;n<billService.list().size();n++){
    		if(billService.list().get(n).getSource().equals("货款"))
    		money=money+billService.list().get(n).getMoney();
    	}
        map.put("money",money);
    	
        return map;
    }
  //按单号查询应还
    @RequestMapping("/seleoddbytotal")
    public Object seleoddbytotal(String odd){
    	List<Odd> list =OddService.list(new QueryWrapper<Odd>().eq("odd", odd));
    	List<Bill> listbill =billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    	int money=0;
    	if(listbill.size()!=0)
    	for (int i = 0; i < listbill.size(); i++) {
			money+=listbill.get(i).getMoney();
		}
    	Map<String, Object> map = new HashMap<>();
        map.put("total",list.get(0).getTotal());
        map.put("money",list.get(0).getTotal()-money);
        
        return map;
    }

    //按电话查询应还
      @RequestMapping("/selephonebytotal")
      public Object selephonebytotal(String phone){
      	List<Odd> list =OddService.list(new QueryWrapper<Odd>().eq("phone", phone).eq("status", 1));
      	int money=0;double total=0.00;
      	for (int i = 0; i < list.size(); i++) {
  			money+=list.get(i).getDebt();
  			total+=list.get(i).getTotal();
  		}
      	Map<String, Object> map = new HashMap<>();
          map.put("total",total);
          map.put("money",money);
          
          return map;
      }
      @PostMapping("/addbillbyphone")
      public Object addbillbyphone(String debt2,String time2,String phone,String money2,String saisie2) throws ParseException{
      	if(Double.parseDouble(money2)>Double.parseDouble(debt2))return "实收金额大于应还金额";
      	List<Odd> list=OddService.list(new QueryWrapper<Odd>().eq("phone", phone).eq("status", 1));

      	String stu="";double moneysum=Double.parseDouble(money2);
      	for (int i = 0; i < list.size(); i++) {
          	Odd oddentity=list.get(i);
      		if(list.get(i).getDebt()==0)continue;//已经还完的货单跳过
      		Bill bill=new Bill();
      		if(moneysum>list.get(i).getDebt()||moneysum==list.get(i).getDebt()){
      			System.out.println("moneysum>list.get(i).getDebt()");
                  bill.setMoney(list.get(i).getDebt());
                  moneysum=moneysum-list.get(i).getDebt();
              	oddentity.setDebt(0.00);
              	
              	bill.setOdd(list.get(i).getOdd()+"");
                  bill.setTotal(list.get(i).getTotal());
                  bill.setDebt(list.get(i).getTotal());
                  bill.setSource("货款");
                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  bill.setTime(simpleDateFormat.parse(time2));
                  bill.setRemark("程序按电话还款");
                  bill.setSaisie(saisie2);
                  bill.setAnq(list.get(i).getAnq());
                  bill.setName(list.get(i).getName2());
                  bill.setPhone(list.get(i).getPhone());
                  bill.setStatus(1);
                  if (billService.save(bill)){
                  	OddService.updateById(oddentity);
                  	stu="添加成功";
                  }else {
                  	stu="添加失败";
                  } 
      		}else{
      			System.out.println("moneysum<list.get(i).getDebt()");
                  bill.setMoney(moneysum);
              	oddentity.setDebt(oddentity.getDebt()-moneysum);
              	
              	bill.setOdd(list.get(i).getOdd()+"");
                  bill.setTotal(list.get(i).getTotal());
                  bill.setDebt(list.get(i).getTotal());
                  bill.setSource("货款");
                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  bill.setTime(simpleDateFormat.parse(time2));
                  bill.setRemark("程序按电话还款");
                  bill.setSaisie(saisie2);
                  bill.setAnq(list.get(i).getAnq());
                  bill.setName(list.get(i).getName2());
                  bill.setPhone(list.get(i).getPhone());
                  bill.setStatus(1);
                  if (billService.save(bill)){
                  	OddService.updateById(oddentity);
                  	stu="添加成功";
                  }else {
                  	stu="添加失败";
                  } 
                  break;
      		}
  		}
          return stu;
      }
}
